<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title="isAdd ? '上传' : '编辑'" width="500px">
    <el-upload
      ref="upload"
      :auto-upload="false"
      :http-request="uploadFile"
      :action="solrFileUploadApi"
      :limit="5"
      :headers="headers"
      :file-list="fileList"
      :show-file-list="true"
      type="file"
      accept=".pdf,.PDF,.doc,.DOC,.docx,.DOCX,.txt,.TXT,.ppt,.PPT,.pptx,.PPTX"
      multiple>
      <el-button size="small" type="primary">添加文件</el-button>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add, edit } from '@/api/solrFile'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
export default {
  props: {
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      dialog: false,
      message: '',
      fileList: [],
      formData: {},
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + getToken()
      },
      rules: {
      }
    }
  },
  computed: {
    ...mapGetters([
      'solrFileUploadApi'
    ])
  },
  methods: {
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.loading = true
      if (this.isAdd) {
        this.doAdd()
      } else this.doEdit()
    },
    uploadFile(file) {
      this.formData.append('files', file.file)
    },
    doAdd() {
      this.formData = new FormData()
      this.$refs.upload.submit()
      console.log(this.formData)
      // 真正上传的地方
      add(this.formData).then(res => {
        this.resetForm()
        this.fileList = []
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.init()
      }).catch(err => {
        this.fileList = []
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    doEdit() {
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    resetForm() {
      this.dialog = false
    }
  }
}
</script>

<style scoped>

</style>
